#include "os/queue.h"
#include "os/os.h"
#include "utils/circle_buffer.h"

typedef struct {
	c_buffer_t buffer;
	u16 esize;
}queue_t;

void *queue_create(u16 queue_count, u16 ele_size){
	queue_t *queue = (queue_t *)os_alloc(queue_count * ele_size + sizeof(queue_t));
	if (queue == NULL) {
		return NULL;
	}
	queue->esize = ele_size;
	circle_buffer_init(&queue->buffer, (u8 *)(queue + 1), queue_count * ele_size);
	return queue;
}

void *queue_create_with_buffer(void *buffer, int32_t size, u16 ele_size) {
	queue_t *queue = (queue_t *)os_alloc(sizeof(queue_t));
	if (queue == NULL) {
		return NULL;
	}
	queue->esize = ele_size;
	circle_buffer_init(&queue->buffer, (u8 *)buffer, size);
	return queue;
}

bool queue_put(co_queue_t vqueue, void *data){
	queue_t *queue = (queue_t *)vqueue;
	if (circle_get_write_space(&queue->buffer) < queue->esize) {
		return false;
	}
	if (circle_put_bytes(&queue->buffer, data, queue->esize) > 0) {
		return true;
	}
	return false;
}

bool queue_get(co_queue_t vqueue, void *data) {
	queue_t *queue = (queue_t *)vqueue;
	if (circle_get_read_space(&queue->buffer) < queue->esize) {
		return false;
	}
	if (circle_get_bytes(&queue->buffer, data, queue->esize) > 0) {
		return true;
	}
	return false;
}


